package com.knightboy.smartshoes.outerNavigation;

import org.json.JSONArray;
import org.json.JSONObject;

public class ResolvePath {
	//规定的给单片机的转向信号
	private static final int GO_LEFT = 1;
	private static final int GO_RIGHT = 2;
	private static final int GO_FORWORD = 3;
	private static final int GO_BACKWORD = 4;

	//百度给出的应走的方向
    private static int resultDirection = -1;

	/**
	 * 解析百度的返回json数据，获得应该前进的方向
	 * @param jsonString
	 * @return
	 */
	public static int getAPath(String jsonString){
		try{
			//取到steps的第一个
			JSONObject jsonObject = (JSONObject)new JSONObject(jsonString);
			JSONObject jsonObject2 = jsonObject.getJSONObject("result");

			JSONArray jsonArray = jsonObject2.getJSONArray("routes");
			JSONObject jsonObject3 = jsonArray.getJSONObject(0);
			JSONArray stepsArray = jsonObject3.getJSONArray("steps");
			JSONObject astep = stepsArray.getJSONObject(0);
			
			resultDirection = astep.getInt("direction");
		}catch(Exception e){
			e.printStackTrace();
		}
		return resultDirection;
	}

	/**
	 * 获得转向信息
	 * @param aDirection    百度给出的应前进方向
	 * @param yourDirection 用户正在前进的方向
	 * @return              返回转向
	 */
	public static int getADirection(int aDirection, float yourDirection){
		int direction = GO_FORWORD;
		int biggerDirec = aDirection*30;
		//应转向角比现行角大
		if(biggerDirec >= yourDirection){
			float differ = biggerDirec - yourDirection;
			//根据二角差得出转向
			if((0 <= differ && differ <= 45) || (315 <= differ && differ <= 360)){
				return GO_FORWORD;
			}else if(45 < differ && differ < 135){
				return GO_RIGHT;
			}else if(135 <= differ && differ <= 225){
				return GO_BACKWORD;
			}else if(225 < differ && differ < 315){
				return GO_LEFT;
			}
		}else {
			//现行角比应转向角大
			float differ = yourDirection - biggerDirec;
			//根据二角差得出转向
			if((0 <= differ && differ <= 45) || (315 <= differ && differ <= 360)){
				return GO_FORWORD;
			}else if(45 < differ && differ < 135){
				return GO_LEFT;
			}else if(135 <= differ && differ <= 225){
				return GO_BACKWORD;
			}else if(225 < differ && differ < 315){
				return GO_RIGHT;
			}
		}
		return direction;
	}
}
